import 'dart:async';

import 'package:app/core/event/event_bus.dart';
import 'package:app/core/theme/app_icons.dart';
import 'package:app/event/event_type.dart';
import 'package:app/routes/my_routes.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

import '../../global_widgets/info_status.dart';
import 'friend/view.dart';
import 'logic.dart';
import 'message/view.dart';

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
  PageController _pageController;
  final List<Widget> _page = [MessagePage(), FriendPage()];
  final List<BottomNavigationBarItem> _buildItem = [
    BottomNavigationBarItem(icon: Icon(Icons.message_rounded), label: "消息"),
    BottomNavigationBarItem(icon: Icon(Icons.person), label: "好友"),
  ];

  final MainLogic logic = Get.find<MainLogic>();

  DateTime _lastPressedAdt; //上次点击时间 初始化的时候是空，下面会做判断
  StreamSubscription<WsStatusEvent> _streamSubscription;
  @override
  void initState() {
    _pageController = PageController();
    WidgetsBinding.instance.addObserver(this);
    _streamSubscription = eventBus.on<WsStatusEvent>((event) {
      logic.changeStatus(event.isConnect);
    });
    super.initState();
  }

  @override
  void dispose() {
    _streamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MainLogic>(
        // initState: logic.,
        init: logic,
        builder: (logic) {
          return WillPopScope(child: GetBuilder<MainLogic>(
            builder: (logic) {
              return Scaffold(
                appBar: AppBar(
                  elevation: 0,
                  leading: GestureDetector(
                    child: Obx(() {
                      return logic.state.currentStatus.value
                          ? InfoStatusView(
                              status: true,
                              title: logic.state.userName.value,
                            )
                          : InfoStatusView(title: logic.state.userName.value);
                      // return InfoStatusView(
                      //   status: logic.state.currentStatus.value,
                      //   title: logic.state.userName.value,
                      // );
                    }),
                    onTap: () {
                      Get.toNamed(RouteConfig.MINE);
                    },
                  ),
                  leadingWidth: 420.w,
                  actions: [
                    PopupMenuButton(
                      itemBuilder: (BuildContext context) =>
                          <PopupMenuItem<String>>[
                        this.selectView(Icons.search_outlined, '搜索', 'A'),
                        this.selectView(Icons.add, '添加好友', 'B'),
                        this.selectView(AppIcons.scan, '扫一扫', 'C'),
                      ],
                      onSelected: (String action) {
                        // 点击选项的时候
                        switch (action) {
                          case 'A':
                            break;
                          case 'B':
                            break;
                          case 'C':
                            break;
                        }
                      },
                    )
                  ],
                  // toolbarHeight: ,
                ),
                body: PageView(
                  controller: _pageController,
                  children: _page,
                  physics: NeverScrollableScrollPhysics(),
                  onPageChanged: (index) {
                    logic.changeIndex(index);
                  },
                ),
                bottomNavigationBar: Obx(() => BottomNavigationBar(
                      items: _buildItem,
                      currentIndex: logic.state.currentIndex.value,
                      type: BottomNavigationBarType.fixed,
                      onTap: (index) => {
                        logic.changeIndex(index),
                        _pageController.jumpToPage(index)
                      },
                    )),
              );
            },
          ), onWillPop: () async {
            if (_lastPressedAdt == null ||
                DateTime.now().difference(_lastPressedAdt) >
                    Duration(seconds: 2)) {
              //两次点击时间间隔超过1秒则重新计时
              _lastPressedAdt = DateTime.now();
              Fluttertoast.showToast(msg: '连续两次退出');
              return false;
            }
            return true;
          });
        });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive:
        print('生命周期 inactive');
        break;
      case AppLifecycleState.paused:
        print('生命周期 paused');
        break;
      case AppLifecycleState.detached:
        print('生命周期 detached');
        break;
      case AppLifecycleState.resumed:
        print('生命周期 resumed');
        break;
    }
  }

  selectView(IconData icon, String text, String id) {
    return PopupMenuItem<String>(
        value: id,
        child: Row(
          // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Icon(icon, color: Colors.blue),
            SizedBox(
              width: 26.w,
            ),
            Text(
              text,
              textAlign: TextAlign.start,
            ),
          ],
        ));
  }
}
